package udl;

import model.UserModel;
import tool.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
	
	Util util=new Util();
	Connection con=null;

	public void addUser(UserModel user){
        con=util.getConnection();
		String sql="insert into attuser (name,password,adm) values (?,?,?)";
		try {
			PreparedStatement ptmt=con.prepareStatement(sql);
			
			ptmt.setString(1, user.getName());
			ptmt.setString(2, user.getPassword());
			ptmt.setInt(3, user.getAdm());
			ptmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
		}
	}
	public int[] Login(String name,String password)
	{
		int[] num={0,0};
		String p=null;
		con=util.getConnection();
		String sql="select id,password,adm from attuser where name=?";
		try {
			PreparedStatement ptmt=con.prepareStatement(sql);
			ptmt.setString(1,name);
			ResultSet res=ptmt.executeQuery();
			while(res.next())
			{
				p=res.getString("password");
				num[1]=res.getInt("adm");
			}
			if(p==null)
			{
				num[0]=2;
			}
			if(password.equals(p))
			{
				num[0]=1;
			}
			if(p!=null&&!password.equals(p))
			{
				num[0]=-1;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return num;
	}

	public int judges(String name)
	{
		int judge=0;
		int i=0;
		con=util.getConnection();
		String sql="select * from attuser where name=?";
		try {
			PreparedStatement ptmt=con.prepareStatement(sql);
			ptmt.setString(1, name);
			ResultSet res=ptmt.executeQuery();
			while(res.next())
			{
				i++;
			}
			if(i==0)
				judge=1;
        } catch (SQLException e) {
			e.printStackTrace();
		}
		return judge;
	}
	
}
